package org.sunshine.mamadu.gui;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.sunshine.mamadu.Advertisement;
import org.sunshine.mamadu.LocalLogger;

import java.util.logging.Level;

public class FloatingInfoShell {
    Shell internalShell;
    private static final int WIDTH = 200;
    private static final int HEIGHT = 50;
    private static int thisCount = 0;

    Advertisement ad;


    public FloatingInfoShell(final Display display, final Advertisement advertisement) {
        thisCount++;
        this.ad = advertisement;
        internalShell = new Shell(display, SWT.TOOL | SWT.PRIMARY_MODAL);
//        internalShell.setBackground(new Color(display, MainFrame.DEFAULT_BACKROUND));
        internalShell.setSize(WIDTH, HEIGHT);
        internalShell.addDisposeListener(new DisposeListener() {
            public void widgetDisposed(DisposeEvent e) {
                thisCount--;
            }
        });


        int y = display.getBounds().height - 30 - thisCount * (HEIGHT + 1);
        internalShell.setLocation(display.getBounds().width - WIDTH, y);

        internalShell.setLayout(new FillLayout());


        Label label = new Label(internalShell, SWT.LEFT | SWT.WRAP | SWT.INHERIT_DEFAULT);
        label.setBackground(new Color(display, MainFrame.DEFAULT_BACKROUND));
        label.setText(ad.getName() + ": " + ad.getContent());

        label.addMouseListener(new MouseAdapter() {
            public void mouseUp(MouseEvent e) {
                if (e.button == 1) {
                    display.asyncExec(new Runnable() {
                        public void run() {
                            new AdvertisementDetailWindow(display, ad);
                        }
                    });
                }
                internalShell.dispose();
            }
        });


        internalShell.open();


        new Thread(new Runnable() {
            public void run() {

                try {
                    Thread.sleep(30 * 1000); // 10 sec
                } catch (InterruptedException e) {
                    LocalLogger.LOGGER.log(Level.WARNING, "Info tool closer sleep.", e);
                }


                display.asyncExec(new Runnable() {
                    public void run() {
                        if (!internalShell.isDisposed())
                            internalShell.dispose();
                    }
                });


            }
        }).start();
    }


}
